package com.leetcode.search;

import java.util.ArrayList;
import java.util.List;

public class RestoreIpAddresses {

    List<String> res;
    int[] segment;
    private static final int COUNT = 4;

    public List<String> restoreIpAddresses(String s) {
        res = new ArrayList<String>();
        segment = new int[COUNT];
        dfs(s, 0, 0);
        return res;
    }

    public void dfs(String s, int segId, int start) {
        if (segId == COUNT) {
            if (start == s.length()) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < COUNT; i++) {
                    sb.append(segment[i]);
                    if (i != COUNT - 1) {
                        sb.append('.');
                    }
                }
                res.add(sb.toString());
            }
            return;
        }
        if (start == s.length()) {
            return;
        }
        if (s.charAt(start) == '0') {
            segment[segId] = 0;
            dfs(s, segId + 1, start + 1);
            return;
        }
        int addr = 0;
        for (int end = start; end < s.length(); end++) {
            addr = addr * 10 + (s.charAt(end) - '0');
            if (addr > 0 && addr <= 0xFF) {
                segment[segId] = addr;
                dfs(s, segId + 1, end + 1);
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        String s = "0100000";
        List<String> res = new RestoreIpAddresses().restoreIpAddresses(s);
        System.out.println(res);
    }
}
